import json
import paho.mqtt.client as mqtt
import threading
import queue
import time
from tools.logger import log
import json
import sqlite3
import paho.mqtt.client as mqtt

import  multiprocessing
# MQTT服务器地址

from Mqtt.volumes import thread_post

import threading
import time
from tools.logger import log
from concurrent.futures import ThreadPoolExecutor
import threading
import queue
import time
import  os


# MQTT配置
MQTT_SERVER = "172.16.1.29"
MQTT_PORT = 18832
username = "intranet"
password = "gst@2024_123!"
topic = "IOT/intranet/client/request/prod/#"
publish_topic = "IOT/intranet/server/report/prod/"

# 共享队列
param_queue = queue.Queue()
param_queue1 = queue.Queue()
param_queue2 = queue.Queue()
param_queue3 = queue.Queue()


# 设备操作类（实际使用时替换为您的实现）
class ThreadPost:
  @staticmethod
  def audiostop_post():
    """停止音频播放"""
    log.info("执行音频停止操作")
    thread_post.audiostop_post()

  @staticmethod
  def relay_post():
    """控制继电器"""
    log.info("执行继电器操作")
    thread_post.relay_post()
    # 这里添加实际业务逻辑
    # 例如：发送继电器开关指令

  @staticmethod
  def volume_post():
    """调节音量"""
    log.info("执行音量调节操作")
    thread_post.volume_post()
    # 这里添加实际业务逻辑
    # 例如：发送音量调节指令


class MQTTController:
  def __init__(self):
    self.keep_running = True
    self.client = None
    self.callback_thread = None
    self.thread_post = ThreadPost()  # 初始化设备操作类

  def on_connect(self, client, userdata, flags, rc):
    if rc == 0:
      log.info("成功连接到MQTT代理！")
      client.subscribe(topic)
    else:
      log.error(f"连接失败，错误码：{rc}")

  def on_message(self, client, userdata, message):
    try:
      msg = json.loads(message.payload.decode())
      log.info(f"收到消息: {msg} from {message.topic}")

      param_queue.put(message.topic)
      param_queue1.put(msg.get('publishId'))
      param_queue2.put(msg.get('imei'))
      param_queue3.put(msg.get('cmd'))
    except Exception as e:
      log.error(f"消息处理错误: {str(e)}")

  def callback(self):
    client = mqtt.Client()
    client.username_pw_set(username=username, password=password)
    client.connect(MQTT_SERVER, MQTT_PORT, 60)
    client.loop_start()

    try:
      while self.keep_running:
        try:
          # 从队列获取数据（带超时）
          data = {
            'param': param_queue.get(timeout=1),
            'publishid': param_queue1.get(timeout=1),
            'imei': param_queue2.get(timeout=1),
            'cmd': param_queue3.get(timeout=1)
          }

          # 发布响应
          pub_topic = f"{publish_topic}{data['imei']}"
          response = {
            "cmd": data['cmd'],
            "imei": data['imei'],
            "publishId": data['publishid'],
            "result": "success",
            "resultId": 1,
            "topic": data['param']
          }
          client.publish(pub_topic, json.dumps(response))
          log.info(f"已发送响应: {response}")

        except queue.Empty:
          continue
        except Exception as e:
          log.error(f"回调处理错误: {str(e)}")
    finally:
      client.loop_stop()
      client.disconnect()

  def run_operations(self):
    """执行业务操作序列"""
    operations = [
      ("音频停止", self.thread_post.audiostop_post),
      ("继电器操作", self.thread_post.relay_post),
      ("音量调节", self.thread_post.volume_post)
    ]

    for name, operation in operations:
      try:
        log.info(f"开始执行: {name}")
        operation()
        log.info(f"完成: {name}")
      except Exception as e:
        log.error(f"{name} 操作失败: {str(e)}")

  def start(self):
    """启动服务"""
    self.client = mqtt.Client()
    self.client.username_pw_set(username=username, password=password)
    self.client.on_connect = self.on_connect
    self.client.on_message = self.on_message
    self.client.connect(MQTT_SERVER, MQTT_PORT, 60)
    self.client.loop_start()

    self.callback_thread = threading.Thread(
      target=self.callback,
      daemon=True  # 设置为守护线程
    )
    self.callback_thread.start()

    self.run_operations()

  def stop(self):
    """停止服务"""
    self.keep_running = False
    if self.callback_thread:
      self.callback_thread.join(timeout=2)
    if self.client:
      self.client.disconnect()
    log.info("服务已安全停止")


def main():
  """主循环（每15秒执行一次完整流程）"""

  controller = MQTTController()
  try:
    log.info("============ 开始新周期 ============")
    controller.start()

    # 等待操作完成（可设置超时）
    while controller.keep_running:
      time.sleep(0.1)

  except KeyboardInterrupt:
    log.info("接收到中断信号...")
  except Exception as e:
    log.error(f"执行错误: {str(e)}")
  finally:
    controller.stop()
    log.info("============ 执行结束 ============")





